<template>
	<!-- 主页的map component -->
	<div class="div_map">
		<div id="allmap" ref="allmap"></div>
	</div>
</template>

<script>
	import BMap from 'BMap'

	export default {
		name: "allmap",
		data() {
			return {
				user: '',
				lushu: '',
				carState: 0,
				infoFlag: false, //车辆信息是否显示				
				loc: '',
				point: null,
				arrPois: '',
				distance: '',
				nowLoction:'',
				paytime: '',
				
				points: [], // 公交点的坐标
				routesPoints: [], // 公交路线坐标集
				routesPointsFrist: true,
				
				busFrist:false,
				routesPointsbefore:[],
				routesPointsafter:[],
				nextStation:0,
				
			}

		},
		props: ['arrPois1', 'searchText', 'searchText1', 'run', 'info', 'nowRoute', 'hasCarAndType', 'routes'],
		watch: {
			nowLoction: function(val) {
					if (val != '') {
						let a = JSON.parse(val);
						this.postCarLoc(a);
				}
			},
			arrPois: function() {
				this.daohang();
			},
			run: function(val) {
				console.log(val)
				switch (val) {
					case 1:
						{
							this.runCar(1)
						}
						break;
					case 2:
						{
							this.runCar(2)
						}
						break;
					case 3:{
					
						this.runCar(3)

						}
						break;
					case 4:
						{
							this.runCar(4)
						}break;
				}

			},
			lushu: function(val) {
				this.runCar(this.run)
			},

			info: function(val) {
				this.carState = val.state;
				
				if (val.state == 0) {
					if(val.type == '公交'){
						this.dingwei(3)
						
					}else{
						this.dingwei()
					}
						
						
				}
			},
			hasCarAndType: function(val, old) {
				
				if (val == 2 && old != 1) {
					this.pilyLine(this.arrPois[2], this.arrPois[0], 'red')
				}
				if(val == 4 && old == 10){
					this.busFrist = true;
				}
				
				
			},
			routes:function(val) {
				if(val){
					this.addBusRoute(val)
				}
			
			},
			routesPoints: function(val) {
				if(val.length == 0){
					return;
				}
				let a = [];
				for(let i in val){
					a.push(val[i])
				}
				if (a.length == (this.points.length -1) ){
					if (this.routesPointsFrist == true) {

						let points = [];
						new Promise((r,j)=>{
							let i = 0;
							for(;i<val.length;i++) {
								points.push(...val[i])
								
								}
							for(let k in val){
								console.log(k)
								for(let j in val[k]){
									if(val[k][j].lat == this.info.cur_loc_lat && val[k][j].lng == this.info.cur_loc_lon){
										this.nextStation = parseInt(k);
										break;
									}
								}
							}
							
							if(i == val.length ){
								r(points)
							}
						}).then(points=>{
							let pointsNow = [];
							let pointBefore = [];
							let k = 0;
							for(let i in points){
								if(points[i].lat == this.info.cur_loc_lat && points[i].lng == this.info.cur_loc_lon){
										k = i;
										break;	
								}
							}
							pointsNow = points.filter((item,index)=>{
								
								return index >= k;
							})
							pointBefore = points.filter((item,index)=>index<=k)
							
							this.routesPointsafter.push(pointsNow);
							this.routesPointsbefore.push(pointBefore) ;
							
							this.busRun(pointsNow,pointBefore)
						})
						
						this.routesPointsFrist = false;
					}
				}
			}
		},
		created() {
			this.user = this.$store.state.user[0];
			this.arrPois = this.arrPois1;

		},
		mounted() {
			this.map()

		},
		
		methods: {
			/* 地图初始化*/
			map() {
				var map = new BMap.Map(this.$refs.allmap); // 创建Map实例
				window.map = map //将map变量存储在全局

				map.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的
				map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放

				// 添加带有定位的导航控件
				var navigationControl = new BMap.NavigationControl({
					// 靠左上角位置
					anchor: BMAP_ANCHOR_TOP_LEFT,
					// LARGE类型
					type: BMAP_NAVIGATION_CONTROL_LARGE,

				});
				map.addControl(navigationControl);
				map.centerAndZoom('广州市');

			},
			dingwei(type = 1) {
				if (this.hasCarAndType == 2 || this.hasCarAndType == 4) {
					return;
				}
				if (this.info.cur_loc_lat && this.info.cur_loc_lon) {
					
					let point = new BMap.Point(this.info.cur_loc_lon, this.info.cur_loc_lat)
					if(type == 1){
						let marker = new BMap.Marker(point, {
							// 指定Marker的icon属性为Symbol
							icon:new BMap.Symbol(BMap_Symbol_SHAPE_POINT, {
							scale: 2, //图标缩放大小
							fillColor: "red", //填充颜色
							fillOpacity: 0.8 //填充透明度
						}) ,
							title: '当前位置'
						});
						var label = new BMap.Label("当前位置",{offset:new BMap.Size(20,-10)});
						

						map.addOverlay(marker);
						marker.setLabel(label);

						map.panTo(point);
					}
					if(type == 3){
					
						let marker = new BMap.Marker(point, {
							// 指定Marker的icon属性为Symbol
							icon:new BMap.Icon('http://lbsyun.baidu.com/jsdemo/img/car.png', new BMap.Size(52, 26), {
									anchor: new BMap.Size(27, 13)}),
							title: '当前位置'
						});
						var label = new BMap.Label("当前位置",{offset:new BMap.Size(20,-10)});
						map.addOverlay(marker);
						marker.setLabel(label);
						map.panTo(point);
					}
				} else {
					var geolocation = new BMap.Geolocation();
					geolocation.enableSDKLocation();
					geolocation.getCurrentPosition(function(r) {
						if (this.getStatus() == BMAP_STATUS_SUCCESS) {
							var mk = new BMap.Marker(r.point, {
								// 指定Marker的icon属性为Symbol
								icon: new BMap.Symbol(BMap_Symbol_SHAPE_POINT, {
									scale: 2, //图标缩放大小
									fillColor: "red", //填充颜色
									fillOpacity: 0.8 //填充透明度
								}),
								title: '当前位置'
							});
							map.addOverlay(mk);
							map.panTo(r.point);
						} else {
							alert('failed' + this.getStatus());
						}
					});
				}

			},
			/* 导航小车动*/
			runCar(val) {
				if (val == 1 || val == 3) {
					if (this.lushu) {
						if(this.hasCarAndType != 2 && this.hasCarAndType != 4){
							var allOverlay = map.getOverlays();
							console.log(allOverlay[0].getLabel())
							for (var i = 0; i < allOverlay.length -1; i++){
								if(allOverlay[i].getLabel != undefined){
									if(allOverlay[i].getLabel() != null){
										if(allOverlay[i].getLabel().content == "当前位置"){
											map.removeOverlay(allOverlay[i]);
											break;
										}
									}
								}
								
							}
						}
						let _that = this
						this.lushu.start();
						this.postDriving()
						var i = document.getElementsByTagName('span');
						for (var y of i) {
							if (y.className == 'BMap_Marker BMap_noprint') {
								y.addEventListener('click', () => {
									if (this.infoFlag == false) {
										this.lushu.showInfoWindow()
									} else {
										this.lushu.hideInfoWindow()
									}
									this.infoFlag = !this.infoFlag;
								})
							}
						}
					} else {
						return;
					}
				} else if (val == 2) {
					this.arrPois.splice(0, 3);
					this.deleteDriving();
					if (this.lushu) {
						this.lushu.stop();
					}
					map.clearOverlays();
				} else if (val == 4) {
					this.deleteDriving();
					if (this.lushu) {
						this.lushu.stop();
						map.clearOverlays();

					}
					this.routesPoints = [];
					this.routesPointsafter = [];
					this.routesPointsbefore = [];
					this.routesPointsFrist = true;

				}
			},
			busRun(points,pointsBefore) {
				let landmarkP = []
				let routes = this.routes;
				for (let i in routes) {
					let item = {
						lng: routes[i].lon,
						lat: routes[i].lat,
						html: `${routes[i].name}到了`,
						pauseTime: 2
					}
					landmarkP[i] = item;
				}
				let nextStation = this.routes[this.nextStation+1].name;
				let content =
					`	<div style="color:#000;padding:5px 5px;text-align:left">
								<p style="font-size:14px;color:red; "><span style="color:#000;">车牌号:</span>${this.info.license_num}</p>
								<p style="font-size:14px;color:red;"><span style="color:#000;">车辆类型:</span>${this.info.type}</p>
								<p style="font-size:14px;color:red;"><span style="color:#000;">车辆品牌:</span>${this.info.brand}</p>
								<p style="font-size:14px;color:red;"><span style="color:#000;">车速:</span>${20*3.6}km/h</p>
								<p style="font-size:14px;color:red;"><span style="color:#000;">下一站:</span>${nextStation}</p>

						<div>		
					`

				let polyline = new BMap.Polyline(pointsBefore, {
					strokeColor: 'red',
					strokeWeight: 6,
					strokeOpacity: 1
				});
				map.addOverlay(polyline);
				this.lushu = new BMapLib.LuShu(map, points, {
					defaultContent: content,
					autoView: true, //是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
					icon: new BMap.Icon('http://lbsyun.baidu.com/jsdemo/img/car.png', new BMap.Size(52, 26), {
						anchor: new BMap.Size(27, 13)
					}),
					speed: 200,
					enableRotation: true, //是否设置marker随着道路的走向进行旋转
					landmarkPois: landmarkP,
				});
				this.chongxie()
			},
			daohang() {
				if (this.arrPois.length < 2) {
					return;
				}
				// 实例化一个驾车导航用来生成路线

				let drv = new BMap.DrivingRoute("北京", {
					onSearchComplete: (res) => {
						if (drv.getStatus() == BMAP_STATUS_SUCCESS) {
							let plan = res.getPlan(0);
							let arrPois = [];
							for (let j = 0; j < plan.getNumRoutes(); j++) {
								let route = plan.getRoute(j);
								arrPois = arrPois.concat(route.getPath());
							}
							map.addOverlay(new BMap.Polyline(arrPois, {
								strokeColor: "green",
								strokeWeight: 5,
							}));
							map.setViewport(arrPois);
							let distance = plan.getDistance();
							let time = plan.getDistance(false) / 20;
							let paytime = this.payTime(time);
							this.paytime = paytime;
							this.distance = distance
							let content =
								`	<div style="color:#000;padding:5px 5px;text-align:left">
											<p style="font-size:14px;color:red; "><span style="color:#000;">车牌号:</span>${this.info.license_num}</p>
											<p style="font-size:14px;color:red;"><span style="color:#000;">车辆类型:</span>${this.info.type}</p>
											<p style="font-size:14px;color:red;"><span style="color:#000;">车辆品牌:</span>${this.info.brand}</p>
											<p style="font-size:14px;color:red;"><span style="color:#000;">车速:</span>${20*3.6}km/h</p>
											<p style="font-size:14px;color:red;"><span style="color:#000;">距离:</span>${this.distance}</p>
											<p style="font-size:14px;color:red;"><span style="color:#000;">预计花费时间:</span>${this.paytime}</p>
									<div>		
								`

							this.lushu = new BMapLib.LuShu(map, arrPois, {
								defaultContent: content,
								autoView: true, //是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
								icon: new BMap.Icon('http://lbsyun.baidu.com/jsdemo/img/car.png', new BMap.Size(52, 26), {
									anchor: new BMap.Size(27, 13)
								}),
								speed: 20,
								enableRotation: true, //是否设置marker随着道路的走向进行旋转
								landmarkPois: [],
							});


						}

					}
				});
				drv.search(this.arrPois[0], this.arrPois[1]);
				this.chongxie()
			},
			addBusRoute(way) { //将公交车辆的路线显示出来
				let points = [];
				for (let item in way) {
					let point = new BMap.Point(way[item].lon, way[item].lat);
					points.push(point);
					if (item == 0) {
						let marker = new BMap.Marker(point, {
							title: `出发站：${way[item].name}`,
						});
						let content =
							`<div style="z-index:1">
								<p><span style="color:red;font-size:14px">出发地:</span>${way[item].name}</p>
							</div>`;
						let label = new BMap.Label(content, {
							offset: new BMap.Size(20, -10)
						});
						marker.setLabel(label);

						map.addOverlay(marker);
					} else if (item == way.length - 1) {
						let marker = new BMap.Marker(point, {
							title: `终点站：${way[item].name}`,
						});
						map.addOverlay(marker);

						let content =
							`<div >
								<p><span style="color:red;font-size:14px">目的地:</span>${way[item].name}</p>
							</div>`;
						let label = new BMap.Label(content, {
							offset: new BMap.Size(20, -10)
						});
						marker.setLabel(label);
					} else {
						let marker = new BMap.Marker(point, {
							title: `途径点：${way[item].name}`
						});
						map.addOverlay(marker);
					}
				}
				this.points = points;
				this.routesPoints = [];
				this.routesPoints.length = points.length - 1
				for (let item in points) {

					if (item > 0) {
						let h = parseInt(Math.random() * 360)
						let c = `green`;
						this.pilyLine(points[item - 1], points[item], c, item);
					}

				}
			},
			pilyLine(l1, l2, color = 'red', isBus = 0) { //出发地到现在所在地
				
				let driving = new BMap.DrivingRoute(map, {
					renderOptions: {
						map: map,
						autoViewport: true
					},
					onPolylinesSet: function(routes) {
						let searchRoute = routes[0].getPolyline(); //导航路线
						map.addOverlay(searchRoute);
					},
					onMarkersSet: function(routes) {
						map.removeOverlay(routes[0].marker); //删除起点
						map.removeOverlay(routes[routes.length - 1].marker); //删除终点
					}
				});
				driving.setSearchCompleteCallback(() => {
					let plan = driving.getResults().getPlan(0);
					if (isBus != 0) {
						if (plan.getRoute(0).getRouteType() == BMAP_ROUTE_TYPE_DRIVING) {
							let points = plan.getRoute(0).getPath()
							this.routesPoints.splice(isBus - 1, 1, points)
						}
					}
					for (let i = 0; i < plan.getNumRoutes(); i++) {
						let pts = plan.getRoute(i).getPath();
						//重点在这   这个地方是关于修改颜色的
						let polyline = new BMap.Polyline(pts, {
							strokeColor: color,
							strokeWeight: 4,
							strokeOpacity: 0.5
						});
						map.addOverlay(polyline);
					}
				})
				driving.search(l1, l2);
			},

			chongxie() { //路书中_move 重写
				var _that = this;
				BMapLib.LuShu.prototype._addMarker = function(callback) {
					if (this._marker) {
						this.stop();
						this._map.removeOverlay(this._marker);
						clearTimeout(this._timeoutFlag);
					}
					//移除之前的overlay
					this._overlay && this._map.removeOverlay(this._overlay);
					let marker = new BMap.Marker(this._path[0]);
					this._opts.icon && marker.setIcon(this._opts.icon);
					this._map.addOverlay(marker);
					this._marker = marker;
				}
				BMapLib.LuShu.prototype._move = function(initPos, targetPos, effect) {
					let pointsArr = [initPos, targetPos]; //点数组
					let me = this,
						//当前的帧数
						currentCount = 0,
						//步长，米/秒
						timer = 500,
						step = this._opts.speed / (1000 / timer),
						//初始坐标
						init_pos = this._projection.lngLatToPoint(initPos),
						//获取结束点的(x,y)坐标
						target_pos = this._projection.lngLatToPoint(targetPos),
						//总的步长
						count = Math.round(me._getDistance(init_pos, target_pos) / step);
					this._map.addOverlay(new BMap.Polyline(pointsArr, {
						strokeColor: "red",
						strokeWeight: 6,
						strokeOpacity: 0.5
					})); // 画线 

					if (_that.hasCarAndType == 2) {
						let driving = new BMap.DrivingRoute(map);
						driving.setSearchCompleteCallback(() => {
							let plan = driving.getResults().getPlan(0);
							let distance = plan.getDistance();
							let time = plan.getDistance(false) / 20;
							let paytime = _that.payTime(time);
							_that.paytime = paytime;
							_that.distance = distance;
							let content =
								`	<div style="color:#000;padding:5px 5px;text-align:left">
											<p style="font-size:14px;color:red; "><span style="color:#000;">车牌号:</span>${_that.info.license_num}</p>
											<p style="font-size:14px;color:red;"><span style="color:#000;">车辆类型:</span>${_that.info.type}</p>
											<p style="font-size:14px;color:red;"><span style="color:#000;">车辆品牌:</span>${_that.info.brand}</p>
											<p style="font-size:14px;color:red;"><span style="color:#000;">车速:</span>${20*3.6}km/h</p>
											<p style="font-size:14px;color:red;"><span style="color:#000;">距离:</span>${distance}</p>
											<p style="font-size:14px;color:red;"><span style="color:#000;">预计花费时间:</span>${paytime}</p>
										</div>  `
							me._opts.defaultContent = content;
						})
						driving.search(initPos, _that.arrPois[1]);
					}
					if(_that.hasCarAndType == 4){
						let val = _that.routesPoints
						let nextStation = _that.routes[_that.nextStation+1].name;
						for(let k in val){
							for(let j in val[k]){
								if(val[k][j].lat == pointsArr[0].lat && val[k][j].lng == pointsArr[0].lng){
									_that.nextStation = parseInt(k);
									nextStation = _that.routes[_that.nextStation+1].name
									break;
								}
							}
						}
						let content =
							`	<div style="color:#000;padding:5px 5px;text-align:left">
										<p style="font-size:14px;color:red; "><span style="color:#000;">车牌号:</span>${_that.info.license_num}</p>
										<p style="font-size:14px;color:red;"><span style="color:#000;">车辆类型:</span>${_that.info.type}</p>
										<p style="font-size:14px;color:red;"><span style="color:#000;">车辆品牌:</span>${_that.info.brand}</p>
										<p style="font-size:14px;color:red;"><span style="color:#000;">车速:</span>${20*3.6}km/h</p>
										<p style="font-size:14px;color:red;"><span style="color:#000;">下一站:</span>${nextStation}</p>
									</div>  `
						me._opts.defaultContent = content;
					}


					// 			获取当前的位置
					 			// console.log(pointsArr[0]);
					_that.nowLoction = JSON.stringify(pointsArr[0]);
					//如果小于1直接移动到下一点

					if (count < 1) {
						me._moveNext(++me.i);
						return;
					}
					//两点之间匀速移动
					me._intervalFlag = setInterval(function() {
						//两点之间当前帧数大于总帧数的时候，则说明已经完成移动
						if (currentCount >= count) {
							clearInterval(me._intervalFlag);
							//移动的点已经超过总的长度
							if (me.i > me._path.length) {
								return;
							}
							//运行下一个点
							me._moveNext(++me.i);
						} else {
							currentCount++;
							var x = effect(init_pos.x, target_pos.x, currentCount, count),
								y = effect(init_pos.y, target_pos.y, currentCount, count),
								pos = me._projection.pointToLngLat(new BMap.Pixel(x, y));
							//设置marker
							if (currentCount == 1) {
								var proPos = null;
								if (me.i - 1 >= 0) {
									proPos = me._path[me.i - 1];
								}
								if (me._opts.enableRotation == true) {
									me.setRotation(proPos, initPos, targetPos);
								}
								if (me._opts.autoView) {
									if (!me._map.getBounds().containsPoint(pos)) {
										me._map.setCenter(pos);
									}
								}
							}
							//正在移动

							me._marker.setPosition(pos);
							//设置自定义overlay的位置
							me._setInfoWin(pos);

						}
					}, timer);
				}
			},
			getLocation(point) { // 地址解析
				let geoc = new BMap.Geocoder();
				geoc.getLocation(point, (result) => {
					let addComp = result.addressComponents;
					this.loc = addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " +
						addComp.streetNumber;
					this.dingweiLoc = this.loc;
					this.searchText1 = this.loc;
					this.$refs.input_search1.readOnly = true

				})

			},
			getCarInfoByNum(car_num) { //通过车牌号查询车辆信息
				this.$axios.get('/api/info/carInfoByNum', {
						params: {
							id: car_num
						}
					})
					.then(data => {
						if (data.status == 200) {
							this.nowLoc.lat = this.car.cur_loc_lat;
							this.nowLoc.lon = this.car.cur_loc_lon;
							let point = new BMap.Point(this.nowLoc.lon, this.nowLoc.lat)
						}
					})
					.catch(err => {
						console.log(err)
					})
			},

			postCarLoc(val) { //每当现在位置改变一次就将数据上传至服务器

				let car = {
					id: this.info.id,
					cur_loc_lon: val.lng,
					cur_loc_lat: val.lat
				}
				this.$axios.post('/api/info/updateCarLoc', car)
					.then(data => {
						if (data.status == 200) {

						}
					})
					.catch(err => {
						console.log(err);
					})
			},
			postDriving() { //将行驶信息上传
				if (this.nowRoute != null && this.carState == 1) {
					return;
				}
				let driving = {}
				if(this.arrPois.length == 0){
					driving = {
						user_id: this.user.id,
						car_id: this.info.id,
						dep_place_lon: this.routes[0].lon,
						dep_place_lat: this.routes[0].lat,
						des_lon: this.routes[this.routes.length - 1].lon,
						des_lat:  this.routes[this.routes.length - 1].lat,
						speed: 72
					}
				}else{
					driving = {
						user_id: this.user.id,
						car_id: this.info.id,
						dep_place_lon: this.arrPois[0].lng ,
						dep_place_lat: this.arrPois[0].lat,
						des_lon: this.arrPois[1].lng ,
						des_lat: this.arrPois[1].lat ,
						speed: 72
					}
				}
				
			

				this.$axios.post('/api/user/insertDriving', driving)
					.then(data => {
						if (data.data == 'ok') {
							this.chageCarState(1);
						}
					})
					.catch(err => {
						console.log(err)
					})
			},
			chageCarState(state) { //改变车辆的状态 state 0为未行驶， 1为行驶中
				this.$axios.get('/api/car/chageCarState', {
						params: {
							id: this.info.id,
							state: state
						}
					}, )
					.then(data => {
						if (data.data == 'ok') {
							if (state == 1) {
								if (this.hasCarAndType == 1) {
									this.changeHasCarAndType(2)
								}
								if (this.hasCarAndType == 3) {
									this.changeHasCarAndType(4)

								}
							} else if (state == 0) {
								if (this.hasCarAndType == 2) {
									this.changeHasCarAndType(1)
								}
								if (this.hasCarAndType == 4) {
									this.changeHasCarAndType(3)
								}
								this.dingwei();
							}
						}
					})
					.catch(err => {

					})
			},
			deleteDriving() { //删除driving信息
				this.$axios.get('/api/user/deleteDriving', {
						params: {
							id: this.user.id
						}
					})
					.then(data => {
						if (data.data == 'ok') {
							console.log('deldete Driving ok')
							this.chageCarState(0);
						}
					})
					.catch(err => {
						console.log(err)
					})
			},
			changeHasCarAndType(state) { //改变HasCarAndType
				this.$emit('changeState', state)
			},
			payTime(val) { // 到达目的地的时间时的格式
				val = parseInt(val)
				if (val <= 60) {

					return `${val}秒`
				} else if (val <= 60 * 60) {
					let m = parseInt(val / 60);
					let s = val - m * 60;
					return `${m}分钟${s}秒`
				} else if (val < 24 * 60 * 60) {
					let h = parseInt(val / 3600);
					let m = parseInt(val - 3600 * h);
					let s = val - 3600 * h - m * 60;
					return `${h}小时${m}分钟${s}秒`
				}
			},
		},

	}
</script>

<style scoped lang="less">
	/* 放大缩小地图控件 */
	.BMap_stdMpZoom {
		margin-top: 50px;
	}

	.div_map {
		width: 100%;
		height: 600px;
		top: 80px;

		position: relative;
		overflow: hidden;

		#allmap {
			position: absolute;

			height: 600px;
			top: 0;

			width: 100%;
		}
	}
</style>
